﻿using log4net.Core;
using log4net.Layout;
using log4net.Layout.Pattern;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

namespace WLYT.Admin.WebApi.Component.log4net
{
    public class MyPatternConverter : PatternLayoutConverter
    {
        protected override void Convert(System.IO.TextWriter writer, LoggingEvent loggingEvent)
        {
            if (Option != null)
                WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
            else
                WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
        }

        //通过反射获取传入的日志对象的某个属性的值
        private object LookupProperty(string property, LoggingEvent loggingEvent)
        {
            object propertyvalue = string.Empty;
            PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);

            if (propertyInfo != null)
                propertyvalue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
            return propertyvalue;
        }
    }

    public class MyLayout : PatternLayout
    {
        public MyLayout()
        {
            this.AddConverter("Property", typeof(MyPatternConverter));
        }
    }
}